package com.ithiema.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ithiema.reggie.Service.CategoryService;
import com.ithiema.reggie.Service.DishFlavorService;
import com.ithiema.reggie.Service.DishService;
import com.ithiema.reggie.common.R;
import com.ithiema.reggie.dto.DishDto;
import com.ithiema.reggie.entity.Category;
import com.ithiema.reggie.entity.Dish;
import com.ithiema.reggie.entity.DishFlavor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    //新增菜品
    @CacheEvict(value = "dish",key = "#dishDto.categoryId+'_'+#dishDto.status")
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }

    //菜品分页查询
    @GetMapping("/page")
    private R<Page> page (int page,int pageSize,String name){
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);


        //条件构造器
        LambdaQueryWrapper<Dish> lwp = new LambdaQueryWrapper<>();
        //添加过滤条件
        lwp.like(null != name,Dish::getName,name);
        //添加排序条件
        lwp.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo,lwp);

//把pageInfo中的数据拷贝到resultPage中 (把基本信息拷贝到   在一起的类)
        Page<DishDto> resultPage = new Page<>();
        BeanUtils.copyProperties(pageInfo,resultPage);

        //从数据库中查询到的集合，不包含分类名称
        //getRecords  (获取记录)
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> resultList = records.stream().map(record -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);
            //设置分类名称
            //根据id查询分类对象
            Category category = categoryService.getById(record.getCategoryId());
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        resultPage.setRecords(resultList);

        return R.success(resultPage);
    }


    //菜品修改
    @GetMapping("/{id}")
    private R<DishDto> get(@PathVariable long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //修改菜品信息
    @CacheEvict(value = "dish",allEntries = true)
    @PutMapping
    public R<String> update (@RequestBody DishDto dishDto ){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    //套餐管理里的添加菜品
            //二次修改  把套餐的口味也加上s
    @Cacheable(value = "dish",key = "#dish.categoryId+'_'+#dish.status")
    @GetMapping("/list")
    public R<List<DishDto>> list (Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> lwp = new LambdaQueryWrapper<>();
        //根据分类id精确查找
        lwp.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        lwp.eq(Dish::getStatus,1);
        //添加排序条件
        lwp.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询
        List<Dish> list = dishService.list(lwp);

        //一下是套餐口味查看
        List<DishDto> resultList = list.stream().map(dishItem -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishItem, dishDto);
            //查询菜品的口味
            //select * from dish_flavor where dish_id=1397851668262465537
            LambdaQueryWrapper<DishFlavor> flavorLqw = new LambdaQueryWrapper<>();
            flavorLqw.eq(DishFlavor::getDishId, dishItem.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(flavorLqw);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(resultList);

    }


    //删除菜品+批量删除
    @DeleteMapping
    private R<String> delete (@RequestParam List<Long> ids){
        dishService.removeWithDish(ids);
        return R.success("删除成功");
    }

    //停售
    @PostMapping("/status/{status}")
    private R<String> sales(@PathVariable ("status") Integer status,@RequestParam List<Long> ids){
        dishService.salesWithDish(status,ids);
        return R.success("修改状态成功");
    }
}
